import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth' // 获取令牌
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login', '/preview/personal-record', '/preview/family-files'] // 没有重定向白名单

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，请重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      // const permission_routes =
      //   store.getters.roles && store.getters.roles.length > 0
      // 确定用户是否已通过getUserInfo获得其权限角色
      const userDate = JSON.parse(window.sessionStorage.getItem('user'))
      if (userDate) {
      } else {
        const data = await store.dispatch('user/getUserInfo')
        // console.log(data)
      }
      const permission_routes =
        store.getters.permission_routes &&
        store.getters.permission_routes.length > 0
      if (permission_routes) {
        next()
      } else {
        try {
          // const { roles } = await store.dispatch("user/getInfo")
          // const accessRoutes = await store.dispatch(
          //   "permission/generateRoutes",
          //   roles
          // )
          //  api获取路由的接口
          const authRoutes = await store.dispatch('user/getRouters')
          const accessRoutes = await store.dispatch(
            'permission/generateRoutes',
            authRoutes[0].children
          )
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // 删除令牌并进入登录页面重新登录
          await store.dispatch('user/resetToken')
          Message.error(error || '有错误')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* 没有token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在白名单中直接进入
      next()
    } else {
      // 无权访问的页面将重定向到登录页面。
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
